import sys

from log_parser import LogParser

log = LogParser().ParseFile(sys.argv[1])

max_runs = {}
(last_command, last_run, cumulative_time) = (None, 0, 0)
for command in log:
    if command['command'] == last_command:
        last_run += 1
        cumulative_time += (command['end'] - command['start'])
    else:
        if last_command is not None:
            if not max_runs.has_key(last_command):
                max_runs[last_command] = []
            max_runs[last_command].append((last_run, cumulative_time))
        last_command = command['command']
        last_run = 1
        cumulative_time = command['end'] - command['start']
to_show = map(lambda (command_name, v): (command_name, reduce(lambda acc,(run,time): acc + run, v, 0), reduce(lambda acc,(run,time): acc + time, v, 0), v), max_runs.items())

to_show.sort(key=lambda (command_name, total_calls, total_time, each): -total_time)

print 'Command name\tCalls\tTotal time\t[(Length of run, time of run)]'
for (command_name, calls, total_time, each) in to_show:
    print '%s\t%s\t%s:\t%s' % (command_name, calls, total_time, each)

total_wd = reduce(lambda acc,(command_name, calls, total_time, each): acc + total_time, to_show, 0)
total_test = log[-1]['end']
print '\nTotal: Inside WebDriver: %s, Test: %s (%s%%)' % (total_wd, total_test, float(total_wd) / total_test)
